var llogDiv;
function llog(str) {
	llogDiv = llogDiv || document.getElementById('llog');
	llogDiv.innerHTML += str.replace('\n', '<br/>') + "<br>";
}
Array.prototype.forEach = function(fun /*, thisp*/)
{
	var len = this.length >>> 0;
	if (typeof fun != "function") throw new TypeError();
	for (var i = 0; i < len; i++) if (i in this) fun(this[i], i, this);
};
Object.prototype.forEach = function(fun /*, thisp*/)
{
	var len = this.length >>> 0;
	if (typeof fun != "function") throw new TypeError();
	for (var i = 0; i < len; i++) if (i in this) fun(this[i], i, this);
};
Array.prototype.grep = function(ident) {
	var ret = [];
	if(typeof ident == "string") {
		var exp = RegExp(ident);
		this.forEach(function(iter, index, arr) { exp.test(iter) && ret.push(typeof(iter)=='string'?iter:iter.toString()); });
	} else if(typeof ident == "boolean") {
		this.forEach(function(iter, index, arr) {iter === ident && ret.push(iter);});
	} else {
		this.forEach(function(iter, index, arr) {iter == ident && ret.push(typeof ident == "number"?parseInt(iter):iter);});
	}
	return ret;

};
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
};
function hasClass(el,className){
return RegExp('[\ ]?' + className + '[\ ]?').test(el.className);
}
function $Qr(qS, set) {
	var tagname,classname,id;//,param;
	var buf_set, results_set = [], parent;

	set.forEach(function(set_iter) {
	    try {
		// div.myclass, p#myid, table
		parent = set_iter;
		buf_set = [];
		if(qS.indexOf('.') != -1) {
			if(qS.charAt(0) != '.') {
				// by tagName and className
				buf_set = qS.split('.');
				tagname = buf_set[0]
				classname = buf_set[1]
				buf_set = parent.getElementsByTagName(tagname);
				buf_set.forEach(function(iter) {
					if(hasClass(iter,classname))
						results_set.push(iter);
				});
			} else {
				// by className only
				classname = qS.substring(1);
				buf_set = parent.getElementsByTagName("*");
				buf_set.forEach(function(iter) {
					if(hasClass(iter,classname))
						results_set.push(iter);
				});
			}

		} else if(qS.indexOf('#') != -1) {

			if(qS.charAt(0) != '#') {
				// by tagName and id
				buf_set = qS.split('#');
				tagname = buf_set[0]
				id = buf_set[1]
				buf_set = parent.getElementsByTagName(tagname);
				buf_set.forEach(function(iter) {
					if(iter.id == id)
						results_set.push(iter);
				});
			} else {
				// by id only
				id = qS.substring(1);
				buf_set = parent.getElementsByTagName("*");
				buf_set.forEach(function(iter) {
					if(iter.id == id)
						results_set.push(iter);
				});
			}

		} else {
			results_set = parent.getElementsByTagName(qS);
		}
	    }catch(e) {llog(e.message);}
	}); // forEach set
	return results_set;
}
function $Q(qStr, parent) {
    try {
	var results_set = [];
	var qA = qStr.split(' ');
	var qS;
	parent = parent || document.getElementsByTagName('body')[0];
	while(qA.length > 0) {
		qS = qA.shift();
		results_set = $Qr(qS, (parent == null ? results_set : [parent]) );
		parent == null;
		if(results_set.length == 0)
			return [];
	}
	return results_set;
    }catch(e) {llog(e.message);}
}

function getEnabledFeatureTable()
{
    var table = document.createElement('table'), td, tr;
    table.className = "icons";
    table.appendChild(tr=document.createElement('tbody'));
    tr.appendChild(tr=document.createElement('tr'));
    var tds = $Q("td", document.getElementById('programNav'));
    td = document.createElement('td');
    var logo = $Q("img", document.getElementById('shortinfo'))[0];
    logo.parentNode.removeChild(logo);
    td.appendChild(logo);
    tr.appendChild(td);
    for(i = 0; i < tds.length; i++) {
        if(/enabled/.test(tds[i].className)){
            td = document.createElement('td');
            td.className = tds[i].className;
            td.title = tds[i].title;
            td.style.width = "72px";
            td.innerHTML = " "
            tr.appendChild(td);
        }
    }
    return table;
    var div = document.createElement('div');
    div.style.cssText="width:250px;position:absolute;top:32px;left 0px;filter:alpha(opacity=80);"
    div.align="left";
    div.appendChild(table);
    return div;

}
function findPrograms(pArray, limit, excludeId, excludeCat) {
    var d = new Date();
    var now = d.getTime()/1000;
    var programs = new Array();

alert('hier');
    for( i = 0; i < pArray.length; i++ )
        if ( pArray[i]['start'] > now &&
             ( excludeId == null || excludeId != pArray[i]['id'] ) &&
             ( excludeCat == null || excludeCat != pArray[i]['cat'] ) ) {
            programs.push(pArray[i]);
            limit--;
            if (limit == 0)
                break;
        }

    return programs;
}

function postprocessView() {
  try {
    var content = document.getElementById('flyoutContentFrame');

    for(var i =0, p = content.getElementsByTagName('p');i < p.length; i++) {
        if(p[i].innerHTML.match('kalender')) {
            p[i].parentNode.removeChild(p[i]);
            break;
        }
    }
    content.appendChild(content = document.createElement('div'));
    content.id = "llog";

    $Q('.programPage')[0].id = "flyOutFocus";
    $Q('.shortinfo')[0].id = "shortinfo";
    $Q('.programNav')[0].id = "programNav";
    $Q('.longinfo')[0].id = "longinfo";
    var enabled = getEnabledFeatureTable();
    content = document.getElementById('shortinfo');
    content.parentNode.insertBefore(enabled, content)


    content = document.getElementById('programNav');

    if($Q("table.icons", content)[0] != content.firstChild) {

        var thumb, height, newParent = document.getElementById('shortinfo').parentNode;
        thumb = $Q("div", content.firstChild);
        height = parseInt(thumb[3].parentNode.style.height);
        if(height > 94)
            height = 94;
	thumb[0].style.cssText += "float:right; top: 2px;left: -8px;overflow:hidden; height: "+height+"px";
        thumb[3].style.top = height-3+"px";
        thumb[4].style.top = height-3+"px";
	thumb.forEach(function(el) { 
		el.style.backgroundImage = el.style.backgroundImage.
			replace(/url\(\/img/g, "url(http://tvtid.tv2.dk/img"); 
	});
	newParent.insertBefore(thumb[0], newParent.firstChild);
    }
    content.parentNode.removeChild(content) // remove old programNav
    content = $Q('programLeft')[0];
    if(typeof content != "undefined")
	content.parentNode.removeChild(content) // remove left side stuff

    // create absolute URI's on anchors and images which requires it
    $Q("a").forEach(function(a) {
	if(a.href && !/^http/.test(a.href)) {
		a.href = "http://tvtid.tv2.dk" + (a.href.charAt(0) == '/' ? '' : '/') + a.href;
	}
    });
    if(typeof ontv != "undefined")
		$Q("#longinfo")[0].innerHTML = ontv;


    $Q("img").forEach(function(img) {
	var s = img.src;
	s = s.replace(/file:\/\//, "")
	if(!/^http/.test(s)) {
		img.src = "http://tvtid.tv2.dk" + (s.charAt(0) == '/' ? '' : '/') + s;
	}
    });

    // push content down and make room for 'features'-table
//    content = document.getElementById('shortinfo')
//    while((content = content.previousSibling) != null)
//        if(/episode|originalTitle/.test(content.className))
//            content.style.cssText = "position:relative; top:0px;"
    // We're done, focus for scrolling
    document.body.onmouseover = function () {
        document.getElementById('flyoutFocus').focus();
    }
  }catch(e) { llog(e.message);}
    try {
        content.getElementsByTagName('p')[0].style.cssText = "margin-top:0;padding-top:2px;"
    } catch(ign) {}

}

postprocessView();

if(llogDiv.childNodes.length > 0) {
	llogDiv.insertBefore(document.createElement('hr'), llogDiv.firstChild);
	llogDiv.insertBefore(document.createTextNode("JS Log: "), llogDiv.firstChild);
	llogDiv.insertBefore(document.createElement('hr'), llogDiv.firstChild);
}
